const fs = require('fs');
const path = require('path')

const CompName = 'index.vue';

const FileOption = {
	encoding: 'utf8'
}

const getFiles = ( path ) => {
	return fs.readdirSync( path);
}

const getText = ( path )=> {
	return fs.readFileSync( path , FileOption);
}

// 合并文本内容
const combind = function(){
	let files = arguments;
	let data = Array.prototype.join.call(files, '\n\n');
	fs.writeFileSync(CompName, data, FileOption);
}

const deleteTemplateOption = ( script )=>{
	let reg = /\s*template\s*:\s*__inline\(\s*\'[^\']*\.html\'\s*\)\s*,/;
	return script.replace( reg, '');
}
// 加个缩进
const addIndent = ( text , char = '\t' )=>{
	let spec = '(\n)';
	let reg = new RegExp( spec, 'mg');
	return text.replace(reg, ($0, $1) => {
		return char;
	}).replace(/^/, char);
}

const wrap = ( text, tmpl ) => {
	if( text ){
		text = addIndent( text );
		return tmpl( text );
	}else{
		return '';
	}
}

const JsParser = ( path ) => {
	let text = getText( path );
	text = deleteTemplateOption( text );
	return wrap( text, text => `<script>\n${text}\n</script>`);
}

const LessParser = ( path ) => {
	let text = getText( path );
	return wrap( text, text =>  `<style lang="less">\n${text}\n</style>`);
}

const HtmlParser = ( path ) => {
	let text = getText( path );
	return wrap( text, text =>  `<template>\n${text}\n</template>`);
}

const Parser = {
	js: JsParser,
	es: JsParser,
	html: HtmlParser,
	less: LessParser,
};

exports.run = ()=>{
	console.log('combinding start')
	let paths = getFiles('.');
	combind.apply(null, paths.map( filePath => {
		let ext = path.extname( filePath ).slice(1);
		if( ext in Parser){
			return Parser[ ext ]( filePath );
		}
	}).filter( text => ([text]+'').trim() !=='' ) )
	console.log('combinding end')
}